package com.motu.monstercity.server.game.verticle;

import com.motu.monstercity.module.common.utility.CmdConstant;
import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.monstercity.server.game.timedtask.*;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.threadpool.DBLogManager;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 定时任务主线程（单进程单线程，用于给定时队列静态缓存添加数据）
 */
public class TimeTaskVerticle extends AbstractVerticle {

	public static final Logger logger = LoggerFactory.getLogger(TimeTaskVerticle.class);

	@Override
	public void start(Promise<Void> future) {
		EventBus eb = vertx.eventBus();
		String address = EventBusConstant.getAddress(EventBusConstant.TIME_MAIN);

		MessageConsumer<JsonObject> consumer = eb.consumer(address);
		consumer.handler(message -> {
			try {
				JsonObject receiveInfo = message.body();
				int cmd = receiveInfo.getInteger("cmd");// 接收命令
				JsonObject data = receiveInfo.getJsonObject("data");// 接收JsonObject数据
				logger.info("###receiveInfo cmd:" + cmd + " info:" + receiveInfo.toString());
				switch (cmd) {
					case TimeTaskCmd.MAIN_CHECK_PROCESS:// 检查集群的进程
						checkProcess();
						break;
					case TimeTaskCmd.MAIN_SERVER_FEAST:// 私人派对结算定时任务 加入任务队列
						DelayQueueManager.addServerfeastQueue(new ServerfeastTask(data));
						message.reply(new JsonObject());
						break;
					case TimeTaskCmd.MAIN_WORLD_BOSS:// 世界Boss定时任务 加入任务队列
						DelayQueueManager.addWorldBossQueue(new WorldBossTask(data));
						message.reply(new JsonObject());
						break;
					case TimeTaskCmd.MAIN_SERVER_SNATCH_OFFER:// 物资争夺悬赏的结算任务，加入任务队列
						DelayQueueManager.addServerSnatchOfferQueue(new ServerSnatchOfferTask(data));
						message.reply(new JsonObject());
						break;
				}
			} catch (Throwable e) {
				String errMsg = Tool.getException(e);
				logger.error("TimeTaskVerticle error: " + errMsg);
				DBLogManager.addServerCrashLog(0, errMsg);
			}
		});

		consumer.completionHandler(res2 -> {
			if (res2.succeeded()) {
				logger.info("TimeTaskVerticle handler registration has reached all nodes address:" + address);
				future.complete();
			} else {
				logger.error("TimeTaskVerticle Registration failed! " + res2.cause().toString());
				future.fail(res2.cause());
			}
		});
	}

	/**
	 * 检查集群的进程
	 */
	private void checkProcess() {
		String gmAdress = EventBusConstant.getAddress(EventBusConstant.GAME_GM);
		EventBus eventBus = MainService.getVertx().eventBus();
		JsonObject messageCheck = new JsonObject();
		messageCheck.put("cmd", CmdConstant.GM_CMD_CHECK);
		messageCheck.put("data", new JsonObject().put("type", 1));// 标识是从定时服发起的
		logger.info("check ebName:" + gmAdress + " message:" + messageCheck.toString());
		eventBus.publish(gmAdress, messageCheck);// 广播所有的进程
	}
}
